package mylab.starters.mybatis.injector;

import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import lombok.extern.slf4j.Slf4j;
import mylab.base.constants.DbConst;
import mylab.starters.mybatis.injector.methods.InsertBatch;
import mylab.starters.mybatis.injector.methods.InsertIgnore;
import mylab.starters.mybatis.injector.methods.InsertIgnoreBatch;
import mylab.starters.mybatis.injector.methods.UpdateAllById;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义的 sql 注入
 */
@Slf4j
@Component
public class ExtSqlInjector extends DefaultSqlInjector {

    static final String[] UPDATE_ALL_IGNORE_COLUMNS = new String[]{
            DbConst.COLUMN_TENANT_ID,
            DbConst.COLUMN_CREATER,
            DbConst.COLUMN_UPDATER,
            DbConst.COLUMN_OWNER,
            DbConst.COLUMN_VERSION,
            DbConst.COLUMN_DELETED};

    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {

        List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
        // 插入数据，如果中已经存在相同的记录，则忽略当前新数据
        methodList.add(new InsertIgnore());
        // 批量插入数据，如果中已经存在相同的记录，则忽略当前新数据
        methodList.add(new InsertIgnoreBatch());
        //
        methodList.add(new InsertBatch());

        // UpdateAllById， 根据id完整更新目标实体
        Predicate<TableFieldInfo> predicate = field -> !CharSequenceUtil.equalsAnyIgnoreCase(field.getColumn(), UPDATE_ALL_IGNORE_COLUMNS);
        methodList.add(new UpdateAllById(predicate));

        return methodList;
    }
}
